package com.lizemin.websocketclient.handler;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;


/**
 * 自定义websocket消息处理器
 *
 * @author lizemin
 * @version 1.0
 */
public class SimpleWebSocketClientHandler extends TextWebSocketHandler {

    /**
     * websocket会话，用于发送消息
     */
    private WebSocketSession session;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        this.session = session;
        System.out.println("已和websocket服务端建立连接");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        System.out.println("接收到服务端发过来的消息: " + message.getPayload());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) {
        System.err.println("传输错误: " + exception.getMessage());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        System.out.println("连接已关闭，状态为: " + status);
    }

    public void sendMessage(String message) throws IOException {
        if (isConnected()) {
            session.sendMessage(new TextMessage(message));
        }
    }

    public boolean isConnected() {
        return session != null && session.isOpen();
    }

}